#!/usr/bin/env python3
"""
依赖安装脚本
解决numpy兼容性问题
"""

import subprocess
import sys
import os

# 简单的日志函数，避免依赖loguru
def log_info(message):
    print(f"[INFO] {message}")

def log_success(message):
    print(f"[SUCCESS] {message}")

def log_error(message):
    print(f"[ERROR] {message}")


def run_command(command, description):
    """执行命令"""
    log_info(f"正在{description}...")
    try:
        result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
        log_success(f"{description}成功")
        return True
    except subprocess.CalledProcessError as e:
        log_error(f"{description}失败: {e}")
        log_error(f"错误输出: {e.stderr}")
        return False


def main():
    """主安装流程"""
    log_info("=== 微信小程序抢号程序依赖安装 ===")
    
    # 检查Python版本
    python_version = sys.version_info
    log_info(f"Python版本: {python_version.major}.{python_version.minor}.{python_version.micro}")
    
    if python_version < (3, 7):
        log_error("需要Python 3.7或更高版本")
        return False
    
    # 升级pip
    if not run_command(f"{sys.executable} -m pip install --upgrade pip", "升级pip"):
        return False
    
    # 先卸载可能有冲突的包
    log_info("清理可能冲突的包...")
    packages_to_remove = ["numpy", "opencv-python", "pyautogui"]
    for package in packages_to_remove:
        run_command(f"{sys.executable} -m pip uninstall {package} -y", f"卸载{package}")
    
    # 按顺序安装依赖
    install_commands = [
        (f"{sys.executable} -m pip install numpy>=1.26.0", "安装numpy"),
        (f"{sys.executable} -m pip install pillow==10.1.0", "安装pillow"),
        (f"{sys.executable} -m pip install opencv-python==4.9.0.80", "安装opencv-python"),
        (f"{sys.executable} -m pip install pyautogui==0.9.54", "安装pyautogui"),
        (f"{sys.executable} -m pip install pyyaml==6.0.1", "安装pyyaml"),
        (f"{sys.executable} -m pip install loguru==0.7.2", "安装loguru"),
        (f"{sys.executable} -m pip install scikit-image==0.22.0", "安装scikit-image"),
    ]
    
    for command, description in install_commands:
        if not run_command(command, description):
            log_error(f"安装失败，请手动执行: {command}")
            return False
    
    # 验证安装
    log_info("验证安装...")
    try:
        import numpy
        import cv2
        import pyautogui
        import yaml
        
        log_success("所有依赖安装成功！")
        log_info(f"numpy版本: {numpy.__version__}")
        log_info(f"opencv版本: {cv2.__version__}")
        log_info(f"pyautogui版本: {pyautogui.__version__}")
        
        return True
        
    except ImportError as e:
        log_error(f"依赖验证失败: {e}")
        return False


if __name__ == "__main__":
    success = main()
    if success:
        print("\n" + "="*50)
        print("安装完成！现在可以运行程序了：")
        print("python main.py")
        print("="*50)
    else:
        print("\n" + "="*50)
        print("安装失败，请检查错误信息并手动安装依赖")
        print("="*50)
        sys.exit(1) 